<template>
  <div class="to-allocate-table">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索申请人/用途"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.applicationType" placeholder="申请类型" clearable>
            <el-option 
              v-for="(label, value) in applicationTypeLabelMap" 
              :key="value" 
              :label="label" 
              :value="value" 
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.classroomType" placeholder="教室类型" clearable>
            <el-option 
              v-for="(label, value) in classroomTypeLabelMap" 
              :key="value" 
              :label="label" 
              :value="value" 
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="searchForm.applyDate"
            type="date"
            placeholder="申请日期"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :row-class-name="rowClassName"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="applicationId" label="申请ID" width="80" />
      <el-table-column prop="userName" label="申请人" width="100" />
      <el-table-column prop="applicationType" label="申请类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getApplicationTypeTag(row.applicationType)">
            {{ getApplicationTypeLabel(row.applicationType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="classroomType" label="教室类型" width="100">
        <template #default="{ row }">
          <el-tag type="info">{{ getClassroomTypeLabel(row.classroomType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="expectedPeople" label="预计人数" width="100" />
      <el-table-column prop="applyDate" label="申请日期" width="120">
        <template #default="{ row }">
          {{ formatDate(row.applyDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="timeRange" label="使用时间" width="150">
        <template #default="{ row }">
          {{ row.startTime }} - {{ row.endTime }}
        </template>
      </el-table-column>
      <el-table-column prop="purpose" label="用途" min-width="150" show-overflow-tooltip />
      <el-table-column prop="equipmentNeeds" label="设备需求" width="120" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" size="small" @click="handleAllocate(row)">
              分配教室
            </el-button>
            <el-button type="info" size="small" @click="handleViewDetail(row)">
              查看详情
            </el-button>
            <el-button type="success" size="small" @click="handleViewAllocation(row)">
              查看分配结果
            </el-button>
            <el-button
              v-if="row.classroomId"
              type="danger"
              size="small"
              @click="handleDeleteAllocationRow(row)"
            >删除分配</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty
      v-if="!loading && tableData.length === 0"
      description="暂无待分配申请"
      :image-size="120"
      class="empty-block"
    />

    <!-- 分页 -->
    <div class="table-pagination" v-if="pagination.total > 0">
      <el-pagination
        background
        layout="prev, pager, next, sizes, jumper, ->, total"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
      <el-button
        v-if="selectedRows.length > 0"
        type="primary"
        style="margin-left: 16px;"
        @click="handleBatchAllocate"
      >批量分配 ({{ selectedRows.length }})</el-button>
    </div>

    <!-- 分配教室弹窗 -->
    <el-dialog
      v-model="allocateDialogVisible"
      title="分配教室"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="allocate-content">
        <div class="application-info">
          <h4>申请信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请人">{{ currentApplication?.userName }}</el-descriptions-item>
            <el-descriptions-item label="申请类型">{{ getApplicationTypeLabel(currentApplication?.applicationType || '') }}</el-descriptions-item>
            <el-descriptions-item label="预计人数">{{ currentApplication?.expectedPeople }}人</el-descriptions-item>
            <el-descriptions-item label="申请日期">{{ formatDate(currentApplication?.applyDate || '') }}</el-descriptions-item>
            <el-descriptions-item label="使用时间">{{ currentApplication?.startTime || '' }} - {{ currentApplication?.endTime || '' }}</el-descriptions-item>
            <el-descriptions-item label="用途">{{ currentApplication?.purpose }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="available-classrooms">
          <h4>可用教室</h4>
          <el-table :data="availableClassrooms" @selection-change="handleClassroomSelection">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="classroomCode" label="教室编号" width="120" />
            <el-table-column prop="capacity" label="容量" width="80" />
            <el-table-column prop="equipment" label="设备" min-width="150" />
            <el-table-column prop="location" label="位置" min-width="120" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag type="success">可用</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="allocateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAllocate" :disabled="selectedClassrooms.length === 0">
          确认分配
        </el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="detailDialogVisible" title="申请详情" width="500px">
      <div v-if="currentDetail">
        <p>申请ID：{{ currentDetail.applicationId }}</p>
        <p>申请人：{{ currentDetail.userName }}</p>
        <p>申请类型：{{ currentDetail.applicationType }}</p>
        <p>教室类型：{{ currentDetail.classroomType }}</p>
        <p>预计人数：{{ currentDetail.expectedPeople }}</p>
        <p>申请日期：{{ formatDate(currentDetail.applyDate) }}</p>
        <p>使用时间：{{ currentDetail.startTime }} - {{ currentDetail.endTime }}</p>
        <p>用途：{{ currentDetail.purpose }}</p>
        <p>设备需求：{{ currentDetail.equipmentNeeds }}</p>
        <p>状态：{{ currentDetail.status }}</p>
      </div>
    </el-dialog>

    <el-dialog v-model="allocationDialogVisible" title="分配结果" width="400px">
      <div v-if="currentAllocation">
        <p>教室编号：{{ currentAllocation.classroomCode || currentAllocation.classroomName || '未分配' }}</p>
        <p>教室类型：{{ getClassroomTypeLabel(currentAllocation.classroomType) }}</p>
        <p>分配状态：{{ currentAllocation.classroomId ? '已分配' : '未分配' }}</p>
      </div>
      <template #footer>
        <el-button @click="allocationDialogVisible = false">关闭</el-button>
        <el-button
          v-if="currentAllocation?.allocationId"
          type="danger"
          @click="handleDeleteAllocation"
        >删除分配记录</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { 
  getApplicationTypeLabel, 
  getApplicationTypeTag, 
  getClassroomTypeLabel,
  applicationTypeLabelMap,
  classroomTypeLabelMap,
  getStatusLabel,
  getStatusTag
} from '@/utils/statusMap'
import { getToAllocateApplications, allocateClassrooms, getAllocatedClassrooms, getAvailableClassrooms, deleteAllocation } from '@/api/classroom'
import dayjs from 'dayjs'

// 搜索表单
const searchForm = reactive({
  keyword: '',
  applicationType: '',
  classroomType: '',
  applyDate: ''
})

// 定义类型
interface ApplicationItem {
  applicationId: number
  userName: string
  applicationType: string
  classroomType: string
  expectedPeople: number
  applyDate: string
  startTime: string
  endTime: string
  purpose: string
  equipmentNeeds: string
  status: string
  classroomName?: string
  classroomCode?: string
  classroomId?: number
  allocationId?: number
}

interface ClassroomItem {
  classroomId: number
  classroomCode: string
  capacity: number
  equipment: string
  location: string
  status: string
}

// 表格数据
const tableData = ref<ApplicationItem[]>([])
const loading = ref(false)
const selectedRows = ref<ApplicationItem[]>([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 分配弹窗
const allocateDialogVisible = ref(false)
const currentApplication = ref<ApplicationItem | null>(null)
const availableClassrooms = ref<ClassroomItem[]>([])
const selectedClassrooms = ref<ClassroomItem[]>([])

// 新增 detailDialogVisible、currentDetail、allocationDialogVisible、currentAllocation 两组ref
const detailDialogVisible = ref(false)
const currentDetail = ref<ApplicationItem | null>(null)
const allocationDialogVisible = ref(false)
const currentAllocation = ref<ApplicationItem & { allocationId?: number } | null>(null)

// 获取数据
async function fetchData() {
  loading.value = true
  try {
    // 调用真实后端API
    const res = await getToAllocateApplications({
      ...searchForm,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    })
    // 只展示 status === 'APPROVED' 且 classroomId == null 的申请（即待分配）
    let rawList = []
    if (res.data?.list) {
      rawList = res.data.list
      pagination.total = res.data.total || 0
    } else if (Array.isArray(res.data)) {
      rawList = res.data
      pagination.total = res.data.length
    } else {
      rawList = []
      pagination.total = 0
    }
    tableData.value = rawList.filter((item: any) => item.status === 'APPROVED' && !item.classroomId)
    pagination.total = tableData.value.length
    console.log('tableData', tableData.value)
  } catch (error) {
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
function handleReset() {
  Object.assign(searchForm, {
    keyword: '',
    applicationType: '',
    classroomType: '',
    applyDate: ''
  })
  handleSearch()
}

// 分页处理
function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchData()
}

function handleCurrentChange(page: number) {
  pagination.currentPage = page
  fetchData()
}

// 选择处理
function handleSelectionChange(selection: any[]) {
  selectedRows.value = selection
}

// 分配教室
async function handleAllocate(row: any) {
  currentApplication.value = row
  allocateDialogVisible.value = true
  // 获取可用教室（只传必要参数：日期、时间段、类型、容量）
  try {
    const params = {
      date: row.applyDate,
      startTime: row.startTime,
      endTime: row.endTime,
      classroomType: row.classroomType,
      capacity: row.expectedPeople
    }
    const res = await getAvailableClassrooms(params)
    // 兼容后端返回数组或分页对象
    availableClassrooms.value = Array.isArray(res.data) ? res.data : (res.data?.list || [])
  } catch (error) {
    ElMessage.error('获取可用教室失败')
    availableClassrooms.value = []
  }
}

// 批量分配
async function handleBatchAllocate() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要分配的申请')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定要批量分配 ${selectedRows.value.length} 个申请吗？`,
      '批量分配',
      { type: 'warning' }
    )
    // TODO: 调用批量分配API batchAllocateClassrooms，参数根据后端接口调整
    // await batchAllocateClassrooms(selectedRows.value.map(item => item.applicationId))
    ElMessage.success('批量分配成功')
    fetchData()
  } catch (error) {
    // 用户取消
  }
}

// 查看详情
function handleViewDetail(row: ApplicationItem) {
  currentDetail.value = row
  detailDialogVisible.value = true
}

// 查看分配结果
async function handleViewAllocation(row: ApplicationItem) {
  try {
    const res = await getAllocatedClassrooms(row.applicationId)
    console.log('分配结果API响应:', res)
    // 处理后端返回的数据，兼容不同字段名
    const allocationData = res.data || {}
    const allocationId = allocationData.allocationId || allocationData.id || allocationData.classroomId
    currentAllocation.value = {
      ...allocationData,
      classroomName: allocationData.classroomName || allocationData.classroomCode || '',
      classroomCode: allocationData.classroomCode || allocationData.classroomName || '',
      allocationId // 这里存主键
    }
    console.log('处理后的分配数据:', currentAllocation.value)
    allocationDialogVisible.value = true
  } catch (error) {
    console.error('获取分配结果失败:', error)
    ElMessage.error('获取分配结果失败')
  }
}

// 教室选择
function handleClassroomSelection(selection: any[]) {
  selectedClassrooms.value = selection
}

// 确认分配
async function confirmAllocate() {
  if (selectedClassrooms.value.length === 0 || !currentApplication.value?.applicationId) {
    ElMessage.warning('请选择要分配的教室')
    return
  }
  try {
    const classroomId = selectedClassrooms.value[0].classroomId
    const applicationId = currentApplication.value.applicationId
    if (!classroomId) {
      ElMessage.warning('教室ID无效')
      return
    }
    await allocateClassrooms(applicationId, {
      allocatorId: 1, // TODO: 替换为当前登录用户ID
      classroomId
    })
    ElMessage.success('分配成功')
    allocateDialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('分配失败')
  }
}

function formatDate(date: string) {
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}

function getClassroomDisplayName(allocation: any) {
  return allocation.classroomName || 
         allocation.classroomCode || 
         (allocation.classroomId ? `教室${allocation.classroomId}` : '未分配')
}

function rowClassName() {
  return 'to-allocate-row'
}

async function handleDeleteAllocation() {
  if (!currentAllocation.value?.allocationId) return
  try {
    await ElMessageBox.confirm('确定要删除该分配记录吗？', '提示', { type: 'warning' })
    await deleteAllocation(currentAllocation.value.allocationId)
    ElMessage.success('删除成功')
    allocationDialogVisible.value = false
    fetchData()
  } catch (e) {
    // 用户取消或出错
  }
}

async function handleDeleteAllocationRow(row: any) {
  const allocationId = row.allocationId || row.classroomId
  if (!allocationId) {
    ElMessage.warning('无分配记录可删除')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除该分配记录吗？', '提示', { type: 'warning' })
    await deleteAllocation(allocationId)
    ElMessage.success('删除成功')
    fetchData()
  } catch (e) {
    // 用户取消或出错
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.to-allocate-table {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
}

.search-bar {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.table-pagination {
  margin-top: 16px;
  text-align: right;
}

.allocate-content {
  max-height: 500px;
  overflow-y: auto;
}

.application-info {
  margin-bottom: 24px;
}

.application-info h4 {
  margin-bottom: 16px;
  color: #303133;
}

.available-classrooms h4 {
  margin-bottom: 16px;
  color: #303133;
}

.empty-block {
  margin: 32px 0 0 0;
}

.to-allocate-row:hover {
  background: #F0F2F6 !important;
}

.el-button-group .el-button {
  margin-right: 0 !important;
}
</style> 